<template>
    <div class>
        <div class="row mb-1">
            <div class="col">
                <el-button @click="dialogVisible = true" type="primary">发送短信</el-button>
                <el-button v-if="!tenant_id" @click="liveUrlDialogVisible = true" type="success"
                    style="margin-left: 8px">管理直播URL</el-button>
                <el-button @click="start" type="info" style="margin-left: 8px">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                    刷新
                </el-button>
            </div>
        </div>
        <div class="row mb-1">
            <div class="col">
                <el-table :data="tableData" border height="68vh" style="width: 100%">
                    <el-table-column prop="ID" label="ID" width="120"></el-table-column>
                    <el-table-column prop="username" label="用户名称" width=""></el-table-column>
                    <el-table-column prop="phonenum" label="手机号码" width=""></el-table-column>
                    <el-table-column prop="state" label="发送状态" width="100"
                        :formatter="({ state }) => state ? '成功' : '失败'">
                    </el-table-column>
                    <el-table-column prop="message" label="失败原因" width="300" show-overflow-tooltip>
                        <template #default="{ row }">
                            <span v-if="!row.state && row.message" class="error-message">{{ row.message }}</span>
                            <span v-else-if="row.state" class="success-message">发送成功</span>
                            <span v-else class="pending-message">-</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createdAt" width="" sortable="custom"
                        :formatter="({ createdAt }) => TimeYH(createdAt)" label="发布时间"></el-table-column>
                </el-table>
            </div>
        </div>
        <el-pagination class="pager" :hide-on-single-page="true" @current-change="handleCurrentChange"
            :page-size="Number(formquery._limit)" layout="prev, pager, next" :total="count"></el-pagination>

        <el-dialog draggable title="短信通知" v-model="dialogVisible" width="800">
            <template #header>
                <span class="icon-text el-dialog__header-title">
                    <el-icon class="text-primary">
                        <Guide />
                    </el-icon>
                    短信通知
                </span>
            </template>

            <el-form :model="ruleForm" label-width="120px" class="sms-form">
                <el-form-item label="选择短信模板">
                    <el-select v-model="ruleForm.codeid" placeholder="请选择短信模板" style="width: 100%" clearable>
                        <el-option v-for="item in sms" :key="item.templateCode" :value="item.templateCode"
                            :label="item.templateName">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="模板内容">
                    <div class="template-preview">
                        {{ previewContent || '请先选择短信模板' }}
                    </div>
                </el-form-item>

                <!-- 模板变量编辑 -->
                <div v-if="templateVariables.length > 0" class="variables-section">
                    <el-divider content-position="left">
                        <el-icon>
                            <Edit />
                        </el-icon>
                        模板变量
                    </el-divider>
                    <div class="variables-container">
                        <div v-for="variable in templateVariables" :key="variable" class="variable-item">
                            <div class="variable-header">{{ variable }}</div>

                            <div class="variable-config">
                                <!-- 每个变量的类型选择 -->
                                <el-radio-group v-model="ruleForm.variables[variable].type" class="type-selector">
                                    <el-radio-button :value="'text'">自定义文本</el-radio-button>
                                    <el-radio-button :value="'var'">系统变量</el-radio-button>
                                </el-radio-group>

                                <!-- 变量值配置 -->
                                <el-input v-if="ruleForm.variables[variable].type === 'text'"
                                    v-model="ruleForm.variables[variable].value" :placeholder="`请输入${variable}的值`"
                                    clearable>
                                </el-input>

                                <el-select v-else v-model="ruleForm.variables[variable].value" placeholder="请选择系统变量"
                                    style="width: 100%">
                                    <el-option value="name" label="用户姓名">
                                        <div class="system-option">
                                            <el-icon>
                                                <User />
                                            </el-icon>
                                            <span>用户姓名</span>
                                        </div>
                                    </el-option>
                                    <el-option value="phone" label="手机号码">
                                        <div class="system-option">
                                            <el-icon>
                                                <Phone />
                                            </el-icon>
                                            <span>手机号码</span>
                                        </div>
                                    </el-option>
                                </el-select>
                            </div>
                        </div>
                    </div>
                </div>

                <el-form-item label="用户">
                    <el-radio v-model="isAdmin" :value="5" size="large">全部成员</el-radio>
                    <el-radio v-model="isAdmin" :value="0" size="large">学生</el-radio>
                    <el-radio v-model="isAdmin" :value="2" size="large">教师</el-radio>
                    <el-radio v-model="isAdmin" :value="1" size="large">管理员</el-radio>
                    <el-radio v-model="isAdmin" :value="3" size="large">创建者</el-radio>
                    <el-radio v-model="isAdmin" :value="4" size="large">指定人员</el-radio>
                </el-form-item>

                <el-form-item v-if="ruleForm.isAdmin == 4" label="选择人员">
                    <el-select-v2 :style="{}" v-model="ruleForm.userid" :options="getusers" filterable key="id"
                        multiple></el-select-v2>
                </el-form-item>
                <div class="row">
                    <div class="col text-right">
                        <el-button @click="dialogVisible = false">取 消</el-button>
                        <el-button type="primary" @click="submit">确 定</el-button>
                    </div>
                </div>
            </el-form>
        </el-dialog>

        <!-- 直播URL管理弹窗 -->
        <el-dialog draggable title="直播URL管理" v-model="liveUrlDialogVisible" width="60%">
            <template #header>
                <span class="icon-text el-dialog__header-title">
                    <el-icon class="text-primary">
                        <Guide />
                    </el-icon>
                    直播URL管理
                </span>
            </template>
            <div class="live-url-container">
                <!-- 操作按钮 -->
                <div class="row mb-3">
                    <div class="col">
                        <el-button @click="loadLiveUrlList" type="info">
                            <el-icon>
                                <Refresh />
                            </el-icon>
                            刷新
                        </el-button>
                        <!-- <el-button @click="showLiveUrlForm" type="primary">
                            <el-icon>
                                <Plus />
                            </el-icon>
                            新增直播URL
                        </el-button> -->
                    </div>
                </div>
                <!-- 直播URL列表 -->
                <el-table :data="liveUrlList" border style="width: 100%" max-height="400px">
                    <el-table-column prop="ID" label="ID" width="80"></el-table-column>
                    <el-table-column prop="platform" label="平台" width="100"></el-table-column>
                    <el-table-column prop="title" label="标题" width="200" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="url" label="URL" width="250" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="description" label="介绍" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="createdAt" label="创建时间" width="150"
                        :formatter="({ createdAt }) => TimeYH(createdAt)"></el-table-column>
                    <el-table-column label="操作" width="150" fixed="right">
                        <template #default="{ row }">
                            <el-button @click="editLiveUrl(row)">编辑</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <el-pagination class="pager mt-3" :hide-on-single-page="true" @current-change="handleLiveUrlPageChange"
                    :page-size="liveUrlQuery._limit" layout="prev, pager, next" :total="liveUrlCount">
                </el-pagination>
            </div>
        </el-dialog>
        <!-- 直播URL表单弹窗 -->
        <el-dialog draggable title="直播URL" v-model="liveUrlFormVisible" width="600px">
            <template #header>
                <span class="icon-text el-dialog__header-title">
                    <el-icon class="text-primary">
                        <Guide />
                    </el-icon>
                    直播URL
                </span>
            </template>
            <el-form :model="liveUrlForm" label-width="100px" :rules="liveUrlRules" ref="liveUrlFormRef">
                <el-form-item label="平台" prop="platform">
                    <el-input v-model="liveUrlForm.platform" placeholder="请输入直播平台" style="width: 100%"></el-input>
                </el-form-item>
                <el-form-item label="标题" prop="title">
                    <el-input v-model="liveUrlForm.title" placeholder="请输入直播标题"></el-input>
                </el-form-item>
                <el-form-item label="URL" prop="url">
                    <el-input v-model="liveUrlForm.url" placeholder="请输入直播URL"></el-input>
                </el-form-item>
                <el-form-item label="封面图">
                    <el-input v-model="liveUrlForm.cover" placeholder="请输入封面图片URL"></el-input>
                </el-form-item>
                <el-form-item label="介绍">
                    <el-input v-model="liveUrlForm.description" type="textarea" :rows="4" placeholder="请输入直播介绍">
                    </el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="liveUrlFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveLiveUrl" :loading="liveUrlSubmitting">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
import type { OptionType } from 'element-plus/lib/components/select-v2/src/select.types';
import { computed, inject, onMounted, reactive, ref, watch } from 'vue';
import { asyncCreatedSmsv2, asyncCreateOrUpdateLiveUrl, asyncquerySmsTemplateListRequest, asyncSelectLiveUrl, asyncselectsms, Iobj, IquerySmsTemplateListRequest } from '../../../api';
import Studycodemodel from '../../../mysql_interface/studycodemodel';
import { TimeYH } from '../../../util/time';

// 码客行
const tenant_id = inject<string | undefined>('tenant_id', undefined)

const dialogVisible = ref(false)
const liveUrlDialogVisible = ref(false)
const liveUrlFormVisible = ref(false)
const submitting = ref(false)
const liveUrlSubmitting = ref(false)
const tableData = ref<Studycodemodel.Isms[]>([])
const count = ref(0)
const liveUrlList = ref<Studycodemodel.Iliveurl[]>([])
const liveUrlCount = ref(0)
const liveUrlFormRef = ref()

const prop = defineProps<{ ID: number | string, team: Studycodemodel.Iteam, teamusers: Studycodemodel.Iteamuser[] }>()

const formquery = reactive<Iobj<Studycodemodel.Isms>>({
    _offset: 0,
    _limit: 20
})

const isAdmin = ref(0)

const sms = ref<IquerySmsTemplateListRequest[]>([])

const ruleForm = reactive<any>({
    teamid: prop.ID,
    userid: [],
    codeid: '',
    isAdmin: 0,
    variables: {}
})

const liveUrlQuery = reactive<Iobj<Studycodemodel.Iliveurl>>({
    _offset: 0,
    _limit: 10
})

const liveUrlForm = reactive<Studycodemodel.Iliveurl>({
    ID: undefined,
    platform: '',
    title: '',
    url: '',
    cover: '',
    description: ''
})

const liveUrlRules = {
    // platform: [{ required: true, message: '请选择直播平台', trigger: 'change' }],
    // title: [{ required: true, message: '请输入直播标题', trigger: 'blur' }],
    url: [{ required: true, message: '请输入直播URL', trigger: 'blur' }]
}

// 解析模板变量
const templateVariables = computed(() => {
    const template = sms.value.find(e => e.templateCode === ruleForm.codeid)
    if (!template?.templateContent) return []

    const matches = template.templateContent.match(/\$\{([^}]+)\}/g)
    if (!matches) return []

    return [...new Set(matches.map(match => match.slice(2, -1)))]
})

// 计算当前选中模板的内容
const currentTemplateContent = computed(() => {
    const template = sms.value.find(e => e.templateCode === ruleForm.codeid)
    return template?.templateContent || ''
})

// 预览内容（替换变量后的内容）
const previewContent = computed(() => {
    let content = currentTemplateContent.value
    if (!content) return ''

    templateVariables.value.forEach(variable => {
        let value = ruleForm.variables[variable]?.value || `\${${variable}}`
        content = content.replace(new RegExp(`\\$\\{${variable}\\}`, 'g'), value)
    })

    return content
})

// 加载直播URL列表
async function loadLiveUrlList() {
    try {
        const data = await asyncSelectLiveUrl(liveUrlQuery)
        liveUrlList.value = data.rows
        liveUrlCount.value = data.count
    } catch (error) {
        console.error('获取直播URL列表失败:', error)
        ElMessage.error('获取直播URL列表失败')
    }
}

// 显示新增表单
function showLiveUrlForm() {
    Object.assign(liveUrlForm, {
        ID: undefined,
        platform: '',
        title: '',
        url: '',
        cover: '',
        description: ''
    })
    liveUrlFormVisible.value = true
}

// 编辑直播URL
function editLiveUrl(row: Studycodemodel.Iliveurl) {
    Object.assign(liveUrlForm, { ...row })
    liveUrlFormVisible.value = true
}

// 保存直播URL
async function saveLiveUrl() {
    if (!liveUrlFormRef.value) return

    try {
        await liveUrlFormRef.value.validate()
        liveUrlSubmitting.value = true

        await asyncCreateOrUpdateLiveUrl(liveUrlForm)
        ElMessage.success(liveUrlForm.ID ? '修改成功' : '新增成功')

        liveUrlFormVisible.value = false
        loadLiveUrlList()
    } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
    } finally {
        liveUrlSubmitting.value = false
    }
}

function handleCurrentChange(val: number) {
    formquery._offset = Number(formquery._limit) * (val - 1);
}

async function submit() {
    // 检查模板变量是否都有值
    if (templateVariables.value.length > 0) {
        const emptyVariables = templateVariables.value.filter(variable => {
            const variableConfig = ruleForm.variables[variable]
            return !variableConfig || !variableConfig.value || variableConfig.value.trim() === ''
        })

        if (emptyVariables.length > 0) {
            ElMessage.error(`请填写完整的模板变量: ${emptyVariables.join(', ')}`)
            return
        }
    }

    submitting.value = true
    try {
        // 处理变量数据，告诉后端每条短信的变量配置
        const submitData = {
            ...ruleForm,
            templateVariables: templateVariables.value // 发送变量列表
        }
        await asyncCreatedSmsv2(submitData)
        dialogVisible.value = false
        start()
    } finally {
        submitting.value = false
    }
}

// 分页处理
function handleLiveUrlPageChange(val: number) {
    liveUrlQuery._offset = Number(liveUrlQuery._limit) * (val - 1)
    loadLiveUrlList()
}

// 监听模板变化，重置变量
watch(() => ruleForm.codeid, () => {
    ruleForm.variables = {}
    // 为新模板的变量设置默认值
    templateVariables.value.forEach(variable => {
        ruleForm.variables[variable] = {
            type: 'text',
            value: ''
        }
    })
})

watch(formquery, e => {
    start()
})

watch(() => isAdmin.value, (v) => {
    if (v == 3) {
        ruleForm.userid = [prop.team.userid]
    } else if (v == 5) {
        ruleForm.userid = getusers.value.map(e => e.value)
    } else {
        ruleForm.userid = []
        ruleForm.isAdmin = v
    }
})

watch(() => dialogVisible.value, (newVal) => {
    if (!newVal) {
        // 弹窗关闭时重置表单
        ruleForm.codeid = ''
        ruleForm.userid = []
        ruleForm.isAdmin = 0
        ruleForm.variables = {}
        isAdmin.value = 0
    }
})

watch(() => liveUrlDialogVisible.value, (newVal) => {
    if (newVal) {
        loadLiveUrlList()
    }
})

const getusers = computed<OptionType[]>(() => {
    return prop.teamusers.map(user => ({
        value: user.userid,
        label: `${user.user?.name || '未知'} (${user.user?.phonenum || ''})`
    }))
})

async function start() {
    try {
        formquery.teamid = prop.ID
        const data = await asyncselectsms(formquery)
        tableData.value = data.rows
        count.value = data.count
    } catch (error) {
        console.error('获取短信记录失败:', error)
        ElMessage.error('获取短信记录失败')
    }
}

async function loadSmsTemplates() {
    try {
        const templates = await asyncquerySmsTemplateListRequest()
        sms.value = templates
    } catch (error) {
        console.error('获取短信模板失败:', error)
        ElMessage.error('获取短信模板失败')
    }
}

onMounted(() => {
    start()
    loadSmsTemplates()
})
</script>

<style scoped>
.dialog-header {
    display: flex;
    align-items: center;
    gap: 8px;
}

.header-icon {
    color: #409eff;
}

.template-preview {
    padding: 12px;
    background-color: #f5f7fa;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    color: #606266;
    font-size: 14px;
    line-height: 1.5;
    white-space: pre-wrap;
    min-height: 60px;
}

.variables-section {
    margin: 20px 0;
}

.variables-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 16px;
    margin-top: 16px;
}

.variable-item {
    background: #f8f9fa;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    padding: 12px;
}

.variable-header {
    font-weight: 500;
    color: #303133;
    margin-bottom: 8px;
    font-size: 14px;
}

.variable-config {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.type-selector {
    display: flex;
    justify-content: center;
}

.system-option {
    display: flex;
    align-items: center;
    gap: 8px;
}

.live-url-container {
    padding: 8px 0;
}

.live-url-container .el-table {
    margin-bottom: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .variables-container {
        grid-template-columns: 1fr;
    }
}
</style>